package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"net/http"
	"news/global"
)

// Check 权限鉴定
func Check() gin.HandlerFunc {
	return func(context *gin.Context) {
		t := context.Request.Header.Get("token")
		if len(t) < 149 || len(t) > 149 {
			context.JSON(http.StatusUnauthorized, map[string]string{
				"msg": "token非法",
			})
			context.Abort()
			return
		}
		if t == "" {
			context.JSON(http.StatusUnauthorized, map[string]string{
				"msg": "请登录",
			})
			context.Abort()
			return
		}
		token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
			return []byte(global.Config.JWTInfo.SigningKey), nil
		})
		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			global.User = claims["iss"]
		}
		if token.Valid {
		} else if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				context.JSON(http.StatusUnauthorized, map[string]string{
					"msg": "令牌错误",
				})
				context.Abort()
				return
			} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
				context.JSON(http.StatusUnauthorized, map[string]string{
					"msg": "令牌已过期",
				})
				context.Abort()
				return
			} else {
				context.JSON(http.StatusUnauthorized, map[string]string{
					"msg": "令牌验证失败",
				})
				context.Abort()
				return
			}
		} else {
			context.JSON(http.StatusUnauthorized, map[string]string{
				"msg": "令牌验证失败",
			})
			context.Abort()
			return
		}

	}
}
